﻿using System.Collections.Generic;

namespace Snake.Gameplay
{
    public class GameplayCueContainer
    {
        public static List<CueDefine> CueDefines { get; set; } = new List<CueDefine>();

        public GameplayAbilityComponent Owner { get; }

        private readonly Dictionary<string, GameplayCueSpec> _cueSpecs = new Dictionary<string, GameplayCueSpec>();

        public GameplayCueContainer(GameplayAbilityComponent owner)
        {
            Owner = owner;
        }

        private void TryAdd(CueDefine define)
        {
            if (_cueSpecs.ContainsKey(define.Tag))
            {
                return;
            }

            var spec = GameplayFactory.CreateCueSpec(define.cue);
            _cueSpecs.Add(define.Tag, spec);
            spec.Container = this;
            spec.OnEnable();
        }

        private void TryRemove(CueDefine define)
        {
            if (!_cueSpecs.ContainsKey(define.Tag))
            {
                return;
            }

            _cueSpecs.Remove(define.Tag, out var spec);
            spec.OnDisable();
        }

        public void OnUpdate(float dt)
        {
            foreach (var define in CueDefines)
            {
                if (!Owner.TagContainer.HasTag(define.Tag))
                {
                    TryRemove(define);
                    continue;
                }

                TryAdd(define);
            }

            foreach (var spec in _cueSpecs.Values)
            {
                spec.OnUpdate(dt);
            }
        }
    }
}